package net.hserver.gateway.core.statistics;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.server.util.HServerIpUtil;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author hxm
 */
@Bean
public class SimpleStatistics implements Statistics {

    private final List<String> android = Collections.singletonList("Android");
    private final List<String> ios = Arrays.asList("iPhone", "iPod", "iPad");
    private final List<String> pc = Arrays.asList("Windows NT", "compatible; MSIE 9.0;");

    @Override
    public void uv(ChannelHandlerContext ctx) {
        StatisticsData.addUv(((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress());
    }

    @Override
    public void pv() {
        StatisticsData.addPv();
    }

    @Override
    public void platform(HttpRequest httpRequest) {
        HttpHeaders headers = httpRequest.headers();
        String agent = headers.get("user-agent");
        String agent1 = headers.get("User-Agent");
        if (agent == null) {
            agent = agent1;
        }
        if (agent == null) {
            StatisticsData.addOtherPlatform();
            return;
        }
        for (String s : pc) {
            if (agent.contains(s)) {
                StatisticsData.addPcPlatform();
                return;
            }
        }
        for (String s : android) {
            if (agent.contains(s)) {
                StatisticsData.addAndroidPlatform();
                return;
            }
        }
        for (String s : ios) {
            if (agent.contains(s)) {
                StatisticsData.addIosPlatform();
                return;
            }
        }
        StatisticsData.addOtherPlatform();
    }
}
